package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetMealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/report")
@PreAuthorize("hasAuthority('REPORT_VIEW')")
public class ReportController {
    @Reference
    private MemberService memberService;

    @Reference
    private SetMealService setMealService;

    @Reference
    private ReportService reportService;

    /*
        会员数量统计
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        //通过Calender对象获取当前日历
        Calendar calendar = Calendar.getInstance();
        //调用Calender中的api
        calendar.add(Calendar.MONTH, -12);//获取当前日期12个之前的日期
        //创建集合,用于存储日期字符串
        List<String> months = new ArrayList<>();
        //使用for循环
        for (int i = 0; i < 12; i++) {
            //每次增加一个月
            calendar.add(Calendar.MONTH, 1);
            //将日期转换成我们想要的格式,在添加进集合中
            months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }
        //创建Map集合用于存储前端需要的数据格式
        Map<String, Object> map = new HashMap<>();
        //将存储日期的集合添加进集合中
        map.put("months", months);

        //调用MemberService,查询会员数量
        List<Integer> memberCount = memberService.findMemberCountBeforeDate(months);
        //将存储会员数量的集合添加进map中
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    /*
        套餐比例统计
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        //创建用于存储响应前端的数据格式
        Map<String, Object> map = new HashMap<>();

        //创建存储套餐名称和套餐预约的人数的集合
        List<Map<String, Object>> setmealCount = setMealService.findSetMealAndCountOrder();
        //将setmealCount集合添加进map
        map.put("setmealCount", setmealCount);

        //创建存储套餐名称的集合
        List<String> setmealNames = new ArrayList<>();

        //遍历集合
        for (Map<String, Object> m : setmealCount) {
            //通过name获取具体的值
            String name = (String) m.get("name");
            //将名称添加进setmealNames集合中
            setmealNames.add(name);
        }
        //将setmealNames集合添加进map中
        map.put("setmealNames", setmealNames);

        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    /*
        运营数据统计
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            //调用服务层
            Result result = reportService.getBusinessReport();
            return result;
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /*
        导出Excel文件
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {

        try {
            //调用服务层,查询Excel文件需要的数据
            Result result = reportService.getBusinessReport();
            //获取数据
            Map<String, Object> map = (Map<String, Object>) result.getData();
            //通过键获取值
            String reportDate = (String) map.get("reportDate");
            Integer todayNewMember = (Integer) map.get("todayNewMember");
            Integer totalMember = (Integer) map.get("totalMember");
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");

            //获取Excel模板文件的磁盘绝对路径
            //File.separator,由于windows和linus下的路径分隔符不一致,使用该api可以自动识别当前系统
            String templateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";

            //创建工作簿对象,读取模板文件
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templateRealPath)));

            //获取第一个工作表对象
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取第三行
            XSSFRow row = sheet.getRow(2);
            //通过行获取第6个单元格,并将日期对象写入到该单元格
            row.getCell(5).setCellValue(reportDate);

            //获取第五行
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);

            //获取第六行
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);

            //获取第八行
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);

            //获取第9行
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);

            //获取第10行
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);

            //设置行为13行
            int rowNum = 12;
            //遍历热门套餐集合
            for (Map map1 : hotSetmeal) {
                //获取集合中的值
                String name = (String) map1.get("name");
                Long setmeal_count = (Long) map1.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map1.get("proportion");
                //获取行
                row = sheet.getRow(rowNum ++);
                //写入数据
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }

            //通过HttpServletResponse获取输出流对象
            ServletOutputStream out = response.getOutputStream();
            //设置文件响应头
            response.setContentType("application/vnd.ms-excel");
            //指定文件已附件形式下载
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");

            //输出
            workbook.write(out);

            //刷新和释放资源
            out.flush();
            out.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /*
        导出PDF文件
     */
    @RequestMapping("/exportBusinessReport4pdf")
    public Result exportBusinessReport4pdf(HttpServletRequest request, HttpServletResponse response) {

        try {

            //调用服务层获取pdf文件需要的数据
            Result result = reportService.getBusinessReport();
            //获取数据
            Map<String, Object> map = (Map<String, Object>) result.getData();
            //获取热门套餐相关的数据
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");

            //获取PDF模板文件的磁盘绝对路径
            //File.separator,由于windows和linus下的路径分隔符不一致,使用该api可以自动识别当前系统
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            //设置编译之后的文件所在路径
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";

            //编译模板,使用JasperCompileManager类
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

            //填充数据,使用JasperFillManager类
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, map, new JRBeanCollectionDataSource(hotSetmeal));

            //通过HttpServletResponse获取输出流对象
            ServletOutputStream out = response.getOutputStream();
            //设置文件响应头
            response.setContentType("application/pdf");
            //指定文件已附件形式下载
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //输出文件,使用JasperExportManager类
            JasperExportManager.exportReportToPdfStream(jasperPrint, out);

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


    /**
     * 获取会员性别,年龄占比
     */
    @RequestMapping("/getAllItemList")
    public Result getAllItemList(){
        System.out.println("getAllItemList is RUNNING...");
       //创建容器
       Map<String,List<Map<String,Integer>>> map = new HashMap<>();
        List<Map<String,Integer>> sexList = new ArrayList<>();
        List<Map<String,Integer>> ageList = new ArrayList<>();
        //获取数据
        sexList = memberService.findMemberSexList();
        ageList = memberService.findMemberAgeList();

        map.put("sexList",sexList);
        map.put("ageList",ageList);

        return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }
}
